#!/usr/bin/python
# Filename: sscmhelper.py
''' Get SCM File History
Call scmhelper's scmhelper method to get the history list.
Author:Ted
Date:2011.09.06
'''

import os
import time
import datetime

class scmhistory:
        def __init__(self, action, user, version, date, comments):
                self.action = action
                self.user = user
                self.version = version
                self.date = date
                self.comments = comments
                
class scmfile:
        def __init__(self, branch, repository, filename, history=None):
                self.branch = branch
                self.repository = repository
                self.filename = filename
                self.history = history
                
class scmhelper:
        ''' SCM history action '''
        historyactions = ['add', 'addtobranch', 'addfrombranch', 'checkin', 'rebase',
                          'rebasewithmerge', 'label', 'attachtodefect', 'delete', 'undelete', 'promotetobranch',
                          'promotefrombranchwithmerge', 'promotefrombranchwithoutmerge', 'share', 'breakshare',
                          'rollbackrebase', 'rollbackpromote', 'rollbackfile']
                
        def getHistoryString(self, branch, repository, filename, startdate, enddate):
                ''' Get the history of specified file.
                branch : string, specify the branch name;
                repository : string, specify the folder name;
                filename: string, specify the file name;
                startdate: string, the format is "yyyyMMdd";
                enddate: string, the format is "yyyyMMdd";
                return the history string.'''
                return os.popen("sscm history \"" + filename + "\" -b\"" + branch + "\" -p\"" + repository + "\" -d\"" + startdate + ":" + enddate + "\"")
        
        def parseHistory(self, historystring):
                ''' parse the history string of specified file to history object list. '''
                historylist = []
                while True:
                        isContnuedComments = False
                        lineText = historystring.readline()
                        if (len(lineText) == 0):
                                return historylist

                        if (lineText.startswith(' Comments')):
                                if (len(historylist) > 0):
                                        isContnuedComments = True
                                        historylist[-1].comments = lineText                                
                        else:
                                # add                                   TedZhao       1         8/23/2011 5:27 PM
                                # the last filed is local datetime format
                                elements = lineText.split()
                                if (len(elements) > 0):
                                        if (elements[0] in scmhelper.historyactions):
                                                isContnuedComments = False
                                                history = scmhistory(elements[0], elements[1], elements[2], " ".join(elements[3:len(elements)]), "")
                                                historylist.append(history)
                                        elif (len(historylist) > 0):
                                                if (isContnuedComments):
                                                        historylist[-1].comments += lineText


        def getHistoryList(self, branch, repository, filename, startdate, enddate):
                ''' Get the history of specified file.
                branch : string, specify the branch name;
                repository : string, specify the folder name;
                filename: string, specify the file name;
                startdate: string, the format is "yyyyMMdd HH:mm:ss";
                enddate: string, the format is "yyyyMMdd HH:mm:ss";
                return the history list.'''
                starttime = time.strptime(startdate, '%Y%m%d %H:%M:%S')
                endtime = time.strptime(enddate, '%Y%m%d %H:%M:%S')

                historystring = self.getHistoryString(branch, repository, filename, time.strftime('%Y%m%d', starttime), time.strftime('%Y%m%d', endtime))
                
                return self.parseHistory(historystring)

        def getScmServerFile(self, folder):    
                folder = folder.replace( "/","\\")

                scmfiles = []
                for root, dirs, files in os.walk(folder):
                        for file in files:            
                            if file == '.MySCMServerInfo':                                
                                scmfiles.append(os.path.join(root, file))

                return scmfiles


        def processScmServerInfoFile(self, filepath, startDate='20100101 00:00:00', endDate='20200101 00:00:00'):
                print filepath
                fileobject = open(filepath)
                branch = ''
                repository = ''
                scmfiles = []

                alllines = fileobject.readlines()
                #print len(alllines)
                try:
                        for line in alllines:                                
                                if (line.startswith('SCMBranch=')):
                                        branch = line[len('SCMBranch='):-1]                                        
                                elif (line.startswith('SCMRepository=')):
                                        repository = line[len('SCMRepository='):-1]
                                else:
                                        filename = line.split(';')[0]
                                        print branch, repository, filename, startDate, endDate
                                        historyList = self.getHistoryList(branch, repository, filename, startDate, endDate)                                        
                                        scmfiles.append(scmfile(branch, repository, filename, historyList))
                
                finally:
                        fileobject.close()
                        return scmfiles
                        
        def getScmFileHistory(self, rootFolder, startDate='20100101 00:00:00', endDate='20200101 00:00:00'):
                files = self.getScmServerFile(rootFolder)
                scmfiles = []
                for scmfile in files:
                        scmfiles = scmfiles + self.processScmServerInfoFile(scmfile, startDate, endDate)

                return scmfiles

if(__name__ == "__main__"):
        helper = scmhelper()
        scmFiles = helper.getScmFileHistory("D:/Workspace/SpreadForSL/Spread/Dev/Source/Silverlight/Spread/Shared/Conditions", "20110101 12:00:00", "20110905 12:00:00")
        
        print(scmFiles[0].branch)
        print(scmFiles[0].repository)
        print(scmFiles[0].filename)
        print(len(scmFiles[0].history))

                                
                        
                        
